#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
简单的Markdown到HTML转换器
"""

import re

def convert_markdown_to_html(md_file_path, output_path):
    """将Markdown文件转换为HTML"""
    
    with open(md_file_path, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # HTML模板
    html_template = '''<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>类小脑计算平台技术规格书</title>
    <style>
        body {{
            font-family: "Microsoft YaHei", Arial, sans-serif;
            line-height: 1.6;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            color: #333;
        }}
        h1, h2, h3, h4, h5, h6 {{
            color: #2c3e50;
            margin-top: 2em;
            margin-bottom: 1em;
        }}
        h1 {{ font-size: 2.5em; border-bottom: 3px solid #3498db; padding-bottom: 10px; }}
        h2 {{ font-size: 2em; border-bottom: 2px solid #3498db; padding-bottom: 8px; }}
        h3 {{ font-size: 1.5em; color: #34495e; }}
        h4 {{ font-size: 1.3em; color: #34495e; }}
        h5 {{ font-size: 1.1em; color: #34495e; }}
        h6 {{ font-size: 1em; color: #34495e; }}
        
        code {{
            background-color: #f8f9fa;
            padding: 2px 4px;
            border-radius: 3px;
            font-family: "Consolas", "Monaco", monospace;
            font-size: 0.9em;
        }}
        
        pre {{
            background-color: #f8f9fa;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            padding: 15px;
            overflow-x: auto;
            margin: 1em 0;
            white-space: pre;
            font-family: "Consolas", "Monaco", monospace;
        }}
        
        table {{
            border-collapse: collapse;
            width: 100%;
            margin: 1em 0;
        }}
        
        th, td {{
            border: 1px solid #ddd;
            padding: 12px;
            text-align: left;
        }}
        
        th {{
            background-color: #f2f2f2;
            font-weight: bold;
        }}
        
        tr:nth-child(even) {{
            background-color: #f9f9f9;
        }}
        
        ul, ol {{
            margin: 1em 0;
            padding-left: 2em;
        }}
        
        li {{
            margin: 0.5em 0;
        }}
        
        hr {{
            border: none;
            border-top: 2px solid #eee;
            margin: 2em 0;
        }}
        
        .ascii-art {{
            font-family: "Consolas", "Monaco", monospace;
            white-space: pre;
            background-color: #f8f9fa;
            padding: 15px;
            border: 1px solid #e9ecef;
            border-radius: 5px;
            overflow-x: auto;
        }}
    </style>
</head>
<body>
{content}
</body>
</html>'''
    
    # 转换Markdown内容
    html_content = convert_md_content(content)
    
    # 生成完整HTML
    full_html = html_template.format(content=html_content)
    
    # 保存HTML文件
    with open(output_path, 'w', encoding='utf-8') as f:
        f.write(full_html)
    
    print(f"转换完成！HTML文件已保存到: {output_path}")
    print("您可以：")
    print("1. 用浏览器打开HTML文件查看效果")
    print("2. 在Word中打开HTML文件，然后另存为.docx格式")

def convert_md_content(content):
    """转换Markdown内容为HTML"""
    lines = content.split('\n')
    html_lines = []
    in_code_block = False
    
    for line in lines:
        # 代码块处理
        if line.startswith('```'):
            if in_code_block:
                html_lines.append('</pre>')
                in_code_block = False
            else:
                html_lines.append('<pre>')
                in_code_block = True
            continue
        
        if in_code_block:
            html_lines.append(line)
            continue
        
        # 标题
        if line.startswith('#'):
            level = 0
            for char in line:
                if char == '#':
                    level += 1
                else:
                    break
            content_text = line[level:].strip()
            html_lines.append(f'<h{level}>{content_text}</h{level}>')
        
        # 分隔线
        elif re.match(r'^-{3,}$', line.strip()):
            html_lines.append('<hr>')
        
        # 列表项
        elif re.match(r'^\s*[-*+]\s+', line):
            content_text = re.sub(r'^\s*[-*+]\s+', '', line)
            html_lines.append(f'<li>{content_text}</li>')
        
        # 数字列表
        elif re.match(r'^\s*\d+\.\s+', line):
            content_text = re.sub(r'^\s*\d+\.\s+', '', line)
            html_lines.append(f'<li>{content_text}</li>')
        
        # 表格行（简化处理）
        elif '|' in line and line.strip().startswith('|'):
            cells = [cell.strip() for cell in line.strip('|').split('|')]
            if not all(re.match(r'^[-:]+$', cell.strip()) for cell in cells):
                row_html = '<tr>'
                for cell in cells:
                    row_html += f'<td>{cell}</td>'
                row_html += '</tr>'
                html_lines.append(row_html)
        
        # 空行
        elif not line.strip():
            html_lines.append('<br>')
        
        # 普通段落
        else:
            # 处理行内代码
            line = re.sub(r'`([^`]+)`', r'<code>\1</code>', line)
            # 处理粗体
            line = re.sub(r'\*\*([^*]+)\*\*', r'<strong>\1</strong>', line)
            html_lines.append(f'<p>{line}</p>')
    
    return '\n'.join(html_lines)

if __name__ == "__main__":
    input_file = "cerebellar_platform_spec_ui_upgraded(1).md"
    output_file = "cerebellar_platform_spec_ui_upgraded.html"
    
    try:
        convert_markdown_to_html(input_file, output_file)
    except Exception as e:
        print(f"转换过程中出现错误: {e}")
        import traceback
        traceback.print_exc()
